import { defineStore } from 'pinia'
import { ref } from 'vue'

// 定义通话邀请数据的类型接口
export interface CallInvitation {
    roomId: string
    callerId: string
    callerName?: string
    callerAvatar?: string
}

// 新增类型用于接收不同格式的参数
type CallInvitationInput =
    | { roomId: string; caller: string }
    | { roomId: string; callerId: string }
    | CallInvitation;

// 创建名为call的Pinia Store
export const useCallStore = defineStore('call', () => {
    // 定义状态（数据）
    const callStatus = ref<'idle' | 'calling' | 'ringing' | 'ending' | 'in_call'>('idle')  // 通话状态
    const currentRoomId = ref('')  // 当前房间ID
    const callerName = ref('')  // 呼叫方名称
    const callerAvatar = ref('')  // 呼叫方头像URL

    // 接收通话邀请
    const receiveCall = (data: CallInvitationInput) => {
        // 统一转换为CallInvitation格式
        const normalizedData: CallInvitation = (() => {
            if ('callerId' in data) return data as CallInvitation;
            if ('caller' in data) {
                return {
                    roomId: data.roomId,
                    callerId: data.caller, // 将caller转换为callerId
                    callerName: data.caller // 同时保留为callerName
                };
            }
            return data;
        })();

        // 更新状态
        currentRoomId.value = normalizedData.roomId;
        callerName.value = normalizedData.callerName || normalizedData.callerId;
        callerAvatar.value = normalizedData.callerAvatar || '';
        callStatus.value = 'ringing';
    };

    // 发送拒绝通知
    const sendRejection = () => {
        if (callStatus.value === 'idle') return;

        console.log('执行拒绝清理');
        callStatus.value = 'idle';
        currentRoomId.value = '';
        callerName.value = '';
    };

    // 暴露状态和方法
    return {
        callStatus,
        currentRoomId,
        callerName,
        callerAvatar,
        receiveCall,
        sendRejection
    }
})